package cascade.controller.pages.commands
{
	import cascade.model.Page;
	import cascade.model.Revision;
	
	import flight.commands.AsyncCommand;
	
	import mx.rpc.Fault;

	public class CommandSavePage extends AsyncCommand
	{
		
		protected var page:Page;
		protected var contents:Array;
		protected var publish:Boolean;
		
		public function CommandSavePage(page:Page, contents:Array, publish:Boolean = false)
		{
			this.page = page;
			this.contents = contents;
			this.publish = publish;
		}
		
		public override function execute():*
		{
			// indicate the app is busy
			Cascade.busy.addBusy(this);
			
			var revision:Revision = Cascade.view.draftMode || !page.liveRevision ? page.draftRevision : page.liveRevision;
			Cascade.service.SiteService.savePage(page.id, revision.id, contents, publish, result, fault);
		}
		
		protected function result(revisions:Array = null):void {
			
			if (publish && revisions)
			{
				page.revisions.removeItemAt(page.revisions.getItemIndex(page.draftRevision));
				page.revisions.addItem(revisions[0]);
				page.revisions.addItem(revisions[1]);
				page.liveRevision = revisions[0];
				page.draftRevision = revisions[1];
			}
			
			// indicate the app is no longer busy
			Cascade.busy.removeBusy(this);
			
			dispatchExecutionComplete();
		}
		
		protected function fault(info:Object):void {
			trace(info);
			// indicate the app is no longer busy
			Cascade.busy.removeBusy(this);
		}
	}
}
